<?php
/**
 * Created by PhpStorm.
 * User: lijie
 * Date: 2018/10/3
 * Time: 13:46
 */
namespace app\api\controller;

use think\Controller;
use think\Request;
use app\api\model\Yearcard as ProductModel;
use app\api\model\YearcardUser;
use app\api\model\Lulog;
use think\Db;


class Year extends Controller{
    public function _initialize()
    {
        parent::_initialize();
        Vendor('WxPay.lib.WxPay#Api');
        Vendor('WxPay.WxPay#JsApiPay');
    }
    /**
     * Notes:  查看年卡充值类型
     * Create Date: 2018/10/3
     * Create by :topqiang
     */
    public function yearCardList(Request $request)
    {
        $param = $request->post();
        $vali  = $this->validate($param,"Year.yearCard");
        if($vali !== true){
            return apiResponse(201,$vali,'');
        }
        $where['status'] = array("neq",9);
        if ( !empty($param['type']) ) {
            $where['type'] = $param['type'];
        }
        $pro = new ProductModel();
        $res['list'] = $pro -> yearCardList($where);
        $res['total'] = $pro->where($where)->count();
        if($res){
            return apiResponse(200,"获取成功！",$res);
        }else {
            return apiResponse(201,"获取失败！",$res);
        }
    }

    /**
     * 
     * @author topqiang
     * @DateTime 2018-09-02T15:27:35+0800
     * @param    Request                  $request [description]
     * @return   [type]                            [description]
     */
    public function myYearCard(Request $request)
    {
        $param = $request->post();
        $vali  = $this->validate($param,"Year.myYearCard");
        if($vali !== true){
            return apiResponse(201,$vali,'');
        }
        $where['end_time'] = array('gt',time());
        $where['u_id'] = $param['u_id'];
        $where['status'] = 1;//1代表已付款
        $pro = new YearcardUser();
        $res['list'] = $pro -> myYearCard($where,$param['pagenum'],$param['listNum']);
        $sql = $pro -> getLastSql();
        
        $res['total'] = $pro->where($where)->count();
        if($res){
            return apiResponse(200,"获取成功！",$res);
        }else {
            return apiResponse(201,"获取失败！",$res);
        }
    }

    
    public function myYearCardLog(Request $request)
    {
        $param = $request->post();
        $vali  = $this->validate($param,"Year.myYearCardLog");
        if($vali !== true){
            return apiResponse(201,$vali,'');
        }
        if (!empty($param['u_id'])) {
            $where['u_id'] = $param['u_id'];
        }
        $where['y_u_id'] = $param['y_id']; 
        $pro = new Lulog();
        if (empty($param['pagenum'])) {
           $param['pagenum'] = 1;
        }
        if (empty($param['listNum'])) {
           $param['listNum'] = 20;
        }
        $res['list'] = $pro -> myYearCardLog($where,$param['pagenum'],$param['listNum']);
        $sql = $pro -> getLastSql();
        $res['total'] = $pro->where($where)->count();
        if($res){
            return apiResponse(200,"获取成功！",$res);
        }else {
            return apiResponse(201,"获取失败！",$res);
        }
    }


    /**
     * Notes:  优惠券详情
     * Create Date: 2018/10/3
     * Create by :lijie
     */
    public function yearInfo()
    {
        $id['id'] = input('post.id');
        if(empty($id)){
            return apiResponse(201,"id不能为空",'');
        }
        //
        $pro = new ProductModel();
        $res = $pro->yearInfo($id);
        if($res){
            return apiResponse(200,'获取成功',$res);
        }else {
            return apiResponse(201,"获取失败",$res);
        }
    }


    public function editYear(Request $request){
        $param = $request->post();
        $vali  = $this->validate($param,"Year.editYear");
        if($vali !== true){
            return apiResponse(201,$vali,'');
        }
        $pro = new ProductModel();
        $res = $pro->isUpdate()->save($param);
        if($res){
            return apiResponse(200,'修改成功！');
        }else {
            return apiResponse(201,"修改失败");
        }
    }

    public function delyear(Request $request){
        $param = $request->post();
        $vali  = $this->validate($param,"Year.delYear");
        if($vali !== true){
            return apiResponse(201,$vali,'');
        }
        $pro = new ProductModel();
        $res = $pro->delYear($param['id']);
        if($res){
            return apiResponse(200,'删除成功！');
        }else {
            return apiResponse(201,"删除失败");
        }
    }


    public function addYear(Request $request){
        $param = $request->post();
        $vali  = $this->validate($param,"Year.addYear");
        if($vali !== true){
            return apiResponse(201,$vali,'');
        }
        $pro = new ProductModel();
        $res = $pro->save($param);
        if($res){
            return apiResponse(200,'添加成功！');
        }else {
            return apiResponse(201,"添加失败");
        }


    }

    


    /**小程序支付
     * @author topqiang
     * @time 2018-10-23
     * @param shop_id 商家的id
     * @param m_id 用户的id
     * @param order_sn 订单号
     */
    public function wxPay(Request $request){
        $param = $request->post();
        $vali  = $this->validate($param,"Year.wxPay");
        if($vali !== true){
            return apiResponse(201,$vali,'');
        }
        $yearCard = new ProductModel();
        $yearCardUser = new YearcardUser();
        $year = $yearCard -> find($param['y_id']);
        if (empty($year)) {
            return apiResponse("201","您购买的年卡不存在");
        }
        /**获取用户的信息*/
        $addarray["u_id"] = $param['u_id'];
        $addarray["y_id"] = $param['y_id'];
        $addarray["type"] = $year['type'];
        $addarray["price"] = $year['price'];
        $addarray["payprice"] = $year['nowprice'];
        $addarray["paynum"] = $year['paynum'];
        $addarray["balance_num"] = $year['paynum'];
        $addarray["balance"] = $year['price'];
        $addarray["create_time"] = time();
        $addarray["title"] = $year['title'];
        $addarray["desc"] = $year['desc'];
        $addarray["ordernumber"] = "ORANGEYEAR".time().mt_rand(100,999);
        $addarray["status"] = 0;

        $addorder = $yearCardUser->save($addarray);
        if($addorder){
            $pricereal = intval($addarray["payprice"]*100);
            if(!is_numeric($pricereal)){
                return apiResponse("201","金额有误","");
            }else{
               $data = $this->wxPayBase($pricereal,$addarray["u_id"],$addarray["ordernumber"]);
                // $data = $this->wxPayBase(1,$addarray["u_id"],$addarray["ordernumber"]);
                header('Content-Type:application/json; charset=utf-8');
                return $data;
            }
        }else{
            return apiResponse("201","生成订单失败","");
        }
    }

    public function manageOrder(){
        //处理订单开始时间和结束时间
        $yearCardUser = new YearcardUser();
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $xml_res = $this->xmlToArray($xml);
        // file_put_contents('res.txt', json_encode($xml_res));

        if($xml_res['return_code'] == 'SUCCESS'){
            $w["ordernumber"] = $xml_res["out_trade_no"];
            file_put_contents('res2.txt',json_encode( $w ));

            $res = $yearCardUser->updateOreder($w);
            file_put_contents('res3.txt', $res);

            if($res){
                $xml = "<xml>
                      <return_code><![CDATA[SUCCESS]]></return_code>
                      <return_msg><![CDATA[OK]]></return_msg>
                    </xml>";
                echo $xml;
            }
        }else{
            file_put_contents('res1.txt', '写不进去');

        }

    }

    /**
     * @param $xml
     * @return mixed
     * ：将xml转为array
     */
    public function xmlToArray($xml)
    {
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }

    public function wxPayBase($pricereal,$u_id,$ordernumber){
        /**获取商家的信息*/
        if(empty($u_id)){
            return apiResponse('201','参数错误',"");
        }
        /**获取用户的信息*/
        $openid = Db::name("user")
                ->field("openid")
                ->where(['u_id'=>$u_id])
                ->find();
        $callback = 'http://'.$_SERVER['HTTP_HOST'].'/api/Year/manageOrder';
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $tools = new \JsApiPay();
        $input->SetOpenid($openid["openid"]);
        $input->SetBody("速西智能洗车");
        $input->SetAttach("速西智能洗车");
        $input->SetGoods_tag("速西智能洗车");
        $input->SetOut_trade_no($ordernumber);
        $input->SetTotal_fee($pricereal);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetNotify_url($callback);
        $input->SetTrade_type("JSAPI");
        $order = \WxPayApi::unifiedOrder($input,6);

        if($order['return_code'] == "FAIL"){
            return apiResponse(201,"未知错误，请联系管理员！",[$pricereal,$u_id,$order,$ordernumber,$openid]);
        }
        if(isset($order['result_code']) && $order['result_code'] == 'FAIL'){
            return apiResponse(201,$order['err_code_des']?$order['err_code_des']:'订单信息错误',"");
        }
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $jsApiParameters = stripslashes($jsApiParameters);
        return apiResponse(200,"成功",$jsApiParameters);
    }

}